package logger;

import java.io.File;
import java.io.RandomAccessFile;
import java.util.Hashtable;

import database.RecordSearch;
import dbmanager.DBManager;
//import file.SearchRecord;
import User.Uservalidation;



public class AddSmsLog 
{
	String path;
	//SearchRecord sr;
	RecordSearch ps;
	DBManager dbSql;
	
	public AddSmsLog(String path)
	{
		this.path = path;
		dbSql =new DBManager();
		dbSql.getConnect();
	}
	
	public boolean Addlog(String username1,String Msg)
	{
		File file = new File(path);
		RandomAccessFile raf ;
		try 
		{
			if(file.exists() == false)
				file.createNewFile();
			if(file.length()==0)
			{
				raf = new RandomAccessFile(file,"rws");
				raf.writeBytes("RECEIVER\t\tMESSAGE\tNumberofSms\tKnownOrUnknown\n");
			}
			else
			{
				raf = new RandomAccessFile(file,"rws");
				raf.seek(raf.getFilePointer());
			}	
			try
			{	
				Hashtable<Object, Object>table = new Hashtable<Object, Object>();
				table.put("RECEIVER",username1);
				/*sr = new SearchRecord(raf);
				String line[] = sr.getRecordSet(table);*/
				ps = new RecordSearch(dbSql);
				ps.setConditionMap(table);
				String line[] = ps.getArrayFromResultSet();
				//int numbersmstsend  = Msg.length()/168;
				if(line.length<1)
				{	
					Uservalidation uservalidation = new Uservalidation(dbSql);
					raf.seek(raf.length());
					if(uservalidation.validate_User(username1))
						raf.writeBytes(username1+"\t"+Msg+"\t"+Integer.toString(1)+"\t"+"Y"+"\n");
					else
						raf.writeBytes(username1+"\t"+Msg+"\t"+Integer.toString(1)+"\t"+"N"+"\n");
					return true;
				}
				else
				{
					String Split[];
					int Numberofsms;
					String last_result = line[line.length-1];
					Split = last_result.split("\t");
					
					Numberofsms = Integer.parseInt(Split[2]);
					Numberofsms++;
					String Known=Split[3];
					
					raf.seek(raf.length());
					if(Known.equals("Y")) 
					{
							if(Numberofsms<=10)
							{
								raf.writeBytes(username1+"\t"+Msg+"\t"+Integer.toString(Numberofsms)+"\t"+Known+"\n");
								return true;
							}	
					}
					else
					{
						if(Numberofsms<1)
						{
							raf.writeBytes(username1+"\t"+Msg+"\t"+Integer.toString(1)+"\t"+Known+"\n");
							return true;
						}	
					}	
				}
			}
			catch (Exception e) 
			{
				e.printStackTrace();
			}
			raf.close();
		}
		catch (Exception e) 
		{
			e.printStackTrace();
		}
		return false;
		
	}
}
